package com.echo.yixiaowu.feature.main.home.bottom

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavDestination.Companion.hasRoute
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.echo.yixiaowu.R
import com.echo.yixiaowu.data.model.BottomNavItem
import com.echo.yixiaowu.route.AppRoute

@Composable
@Preview
fun MainBottomBar(navController: NavHostController = rememberNavController()) {
    val items = listOf(
        BottomNavItem("主页", R.drawable.ic_home, AppRoute.Home),
        BottomNavItem("关注", R.drawable.ic_notice, AppRoute.Follow),
        BottomNavItem("消息", R.drawable.ic_message, AppRoute.Message),
        BottomNavItem("我的", R.drawable.ic_user, AppRoute.Mine)
    )
    NavigationBar(
        modifier = Modifier.fillMaxWidth().height(58.dp),
        containerColor = colorResource(R.color.white),
    ) {
        val navBackStackEntry by navController.currentBackStackEntryAsState()

        items.forEach { (label, icon, item) ->
            NavigationBarItem(
                selected = navBackStackEntry?.destination?.hasRoute(item::class) == true,
                onClick = {
                    navController.navigate(item) {
                        popUpTo(navController.graph.startDestinationId) {
                            saveState = true
                        }
                        // 避免在点击同一按钮时创建多个实例
                        launchSingleTop = true
                        // 恢复以前保存的状态
                        restoreState = true
                    }
                },
                icon = {
                    Icon(
                        painter = painterResource(id = icon),
                        contentDescription = label,
                        tint = Color.Black,
                        modifier = Modifier.size(20.dp)
                    )
                },
                label = {
                    Text(
                        text = label, color = Color.Black, fontSize = 10.sp
                    )
                },
                alwaysShowLabel = true,
            )
        }
    }
}